package com.ds.system.sys.view;

import com.ds.common.JDSException;
import com.ds.esd.custom.annotation.CustomAnnotation;
import com.ds.esd.custom.form.enums.CustomFormMenu;
import com.ds.esd.custom.tree.annotation.TreeAnnotation;
import com.ds.esd.formula.service.FolderFService;
import com.ds.esd.tool.ui.component.list.TreeListItem;
import com.ds.esd.tool.ui.enums.SelModeType;
import com.ds.vfs.Folder;
import com.ds.vfs.ct.CtVfsFactory;

import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@TreeAnnotation(heplBar = true, caption = "选择地址", bottombarMenu = {CustomFormMenu.Save, CustomFormMenu.Close}, selMode = SelModeType.singlecheckbox, customService = {FolderFService.class})
public class FolderTopTree extends TreeListItem {
    @CustomAnnotation(pid = true)
    String pattern = "";
    @CustomAnnotation(pid = true)
    String sysId;


    public FolderTopTree(String pattern) throws JDSException {
        this.caption = "跟目录";
        Folder rootfolder = CtVfsFactory.getCtVfsService().getFolderByPath("form/");
        List<Folder> folders = rootfolder.getChildrenList();
        this.id = "allFolder";

        for (Folder folder : folders) {
            if (checkChild(pattern, folder)) {
                this.addChild(new FolderTopTree(pattern, folder));
            }
        }
    }

    public FolderTopTree(String pattern, Folder folder) {
        this.caption = folder.getDescrition();
        this.setId(folder.getPath());
        this.setIniFold(false);
        this.tagVar = new HashMap<>();
        this.tagVar.put("path", folder.getPath());

    }

    private boolean checkChild(String pattern, Folder folder) {
        if (pattern(pattern, folder)) {
            return true;
        }
        List<Folder> folders = folder.getChildrenList();
        for (Folder childFolder : folders) {
            if (pattern(pattern, childFolder)) {
                return true;
            }
        }
        return false;
    }

    private boolean pattern(String pattern, Folder folder) {

        if (pattern != null && !pattern.equals("")) {
            Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
            Matcher namematcher = p.matcher(folder.getName());
            Matcher cnmatcher = p.matcher(folder.getDescrition());

            if (namematcher.find() || cnmatcher.find()) {
                return true;
            }
        } else {
            return true;
        }

        return false;

    }

    public String getSysId() {
        return sysId;
    }

    public void setSysId(String sysId) {
        this.sysId = sysId;
    }

    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }
}
